<?php

/*
 * To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/**
 * Description of Login
 *
 * @author notobo
 */
if(! defined('BASEPATH'))
	exit('No direct script access allowed');
session_start();

class Login extends CI_Controller{

	public function __construct() {
		parent::__construct();
		$this->load->model('User_model');
		$this->load->model('Log_model');
		$this->load->helper('url');
		$this->load->library('session');
		parse_str( $_SERVER['QUERY_STRING'], $_REQUEST );
		$CI = & get_instance();
		$CI->config->load("facebook",TRUE);
		$config = $CI->config->item('facebook');
		$this->load->library('Facebook', $config);
		//$this->load->library('encrypt');
	}

	public function index(){
		$this->load->view('login');
	}

	public function login_user(){
            $check = false;
            $message = "";
            $cb = $this->input->get_post('callback');
            $username = $this->input->get_post('username');
            $username = htmlspecialchars($username);
            if(strlen($username)== 0){
                $message = 'Phải nhập username';
            }
            $password = $this->input->get_post('password');
            $log = array(
                'action'=>'LOGIN',
                'method'=>$this->router->fetch_method(),
                'username'=>$username,
            );
            try{
                //Kiểm tra xem đã đăng nhập chưa
                $checkSession = $this->check_session();
                if($checkSession){
                    $check = true;
                    $message = "Tài khoản đã đăng nhập";
                    $this->data['json']['username'] = $this->session->userdata('username');
                    $this->data['json']['id'] = $this->session->userdata('id');
                    $this->data['json']['sessionid'] = $this->session->userdata('my_session_id');
                //Nếu chưa thì ghi vào session
                }else{
                    $result = $this->User_model->login($username,$password);
                    if($result){    
                        $userId = $result['id'];
                        $my_session_id = $this->generate_session_id($userId);
                        $session = array(
                            'id'=>$userId,
                            'username'=>$username,
                            'logged_in'=>'true',
                            'my_session_id'=>$my_session_id,
                        );
                        $this->session->set_userdata($session);
                        $check = true;
                        $message = "Đăng nhập thành công";
                        
                        
                        
                        //Ghi session
                        $this->data['json']['username'] = $username;
                        $this->data['json']['id'] = $userId;
                        $this->data['json']['sessionid'] = $this->session->userdata('my_session_id');
                        
                        //Cập nhật session vào database
                        $data = array(
                                'is_logged'=>1,
                                'session_id'=>$my_session_id,
                        );
                        $this->User_model->update_logged_user($userId,$data);
                        
                        //Tạo log
                        $log['user_id']=$userId;
                        $log['result']='OK';
                        $this->Log_model->add_log_from_array($log);
                    }else{
                        $message = "Đăng nhập không thành công, nếu bạn là người mới thì hãy đăng ký một tài khoản";
                    }
                }
                $this->data['json']['status'] = $check;
                $this->data['json']['message'] = $message;               

                echo $cb."(".json_encode($this->data['json']).")";
                exit();
            }catch(Exception $e){
                $log['result']='Error';
                $log['bug']=$e->getMessage();
                $this->Log_model->add_log_from_array($log);
                echo $e->getMessage();
            }
        }

        public function logout_user(){
            $cb = $this->input->get_post('callback');
            $status = true;
            $message = "";              
            $checkSession = $this->check_session();
            if($checkSession){
                $user_id = $this->session->userdata('id');
                //Xóa session trong db
                $data = array(
                    'is_logged'=>0,
                    'session_id'=>'',
                );
                $this->User_model->update_logged_user($user_id,$data);
                $log = array(
                        'user_id'=>$user_id,
                        'username'=>$this->session->userdata('username'),
                        'action'=>'LOGOUT',
                        'method'=>$this->router->fetch_method(),
                        'result'=>'OK',
                 );

                 $this->Log_model->add_log_from_array($log);

                 $this->session->sess_destroy();
                 $this->facebook->destroySession();
                 $status = true;
                 $message = 'Đăng xuất thành công';
      
            }else{
                $status = false;
                $message = 'Đăng xuất không thành công';
            }
            $this->data['json']['status'] = $status;
            //$this->data['json']['message'] = $this->session->userdata('my_session_id')."   ".$this->session->userdata('logged_in');
            $this->data['json']['message'] = $message;
            echo $cb."(".json_encode($this->data['json']).")";                  
        }
  
    public function check_session(){       
        if($this->session->userdata('logged_in')){
                //&& $this->session->userdata('username')
                //    && $this->session->userdata('id')){  
            return TRUE;
        }else{
            return FALSE;
        }
    }
    
    public function check_login(){
        $cb = $this->input->get_post('callback');
        if($this->check_session()){
            $status = true;
            $this->data['json']['username'] = $this->session->userdata('username');
            $this->data['json']['id'] = $this->session->userdata('id');
            $this->data['json']['sessionid'] = $this->session->userdata('my_session_id');
        }else{
            $status = false;
            $this->session->sess_destroy();
        }
        $this->data['json']['status'] = $status;
        echo $cb."(".json_encode($this->data['json']).")";
    }


	public function login_facebook (){
		//var_dump('abc');die();
		$userId = $this->facebook->getUser();

		// If user is not yet authenticated, the id will be zero
		if($userId == 0){
			// Generate a login url
			$url = $this->facebook->getLoginUrl(array('scope'=>'email'));
			redirect($url);
		} else {
			// Get user's data and print it
			// 			$streamQuery =array("basicinfo"=> "SELECT uid,name,pic_square FROM user WHERE uid=me()","friendsinfo" => "SELECT uid, name, pic_square FROM user WHERE uid = me() OR uid IN (SELECT uid2 FROM friend WHERE uid1 = me())");
			// 			$streamParams = array(
			// 					'method' => 'fql.multiquery',
			// 					'queries' => $streamQuery
			// 			);
			// 			$streamResult = $this->facebook->api($streamParams);
			$user = $this->facebook->api(array(
					'method'=>'fql.query',
					'query'=>'SELECT uid,name,username,email,sex,pic_big FROM user WHERE uid=me()'
			));
				
			if (!$this->User_model->check_email($user[0]['email'])){
				
				$name = $user[0]['name'];
				$link = 'https://www.facebook.com/'+$user[0]['username'];
				$email = $user[0]['email'];
				$social_user_id = $user[0]['uid'];
				$gender = $user[0]['sex'];
				$avatar_link = $user[0]['pic_big'];
				$user_id = $this->User_model->facebook_register($name,$link,$email,$social_user_id,$gender,$avatar_link);
				if ($user_id > 0) {
                                        $my_session_id = $this->generate_session_id($user_id);
					$session = array(
							'id'=>$user_id,
							'username'=>$name,
							'logged_in'=>'true',
                                                        'my_session_id'=>$my_session_id,
					);
					//$this->session->set_userdata('logged_in' ,'true');
					$this->session->set_userdata($session);
                                        $data = array(
                                                'is_logged'=>1,
                                                'session_id'=>$my_session_id,
                                        );
                                        $this->User_model->update_logged_user($user_id,$data);
                                        //$session_id = $this->session->userdata('my_session_id');
                                        $params = 'userid='.$user_id.'&username='.$name.'&sessionkey='.$my_session_id;
					redirect('http://dev.innoflex.vn/wordpress/?'.$params);
                                       //echo $params.$this->session->userdata('logged_in').$this->session->userdata('username').$this->session->userdata('id');
				}
			}
			else {                              
				$user_info = $this->User_model->get_user_by_email($user[0]['email']);
                                $my_session_id = $this->generate_session_id($user_info->id);
                                $data = array(
                                        'is_logged'=>1,
                                        'session_id'=>$my_session_id,
                                );
                                $this->User_model->update_logged_user($user_info->id,$data);
				$session = array(
						'id'=>$user_info->id,
						'username'=>$user_info->nickname,
						'logged_in'=>'true',
                                                'my_session_id'=>$my_session_id,
				);
				//$this->session->set_userdata('logged_in' ,TRUE);
				$this->session->set_userdata($session);
                                //$session_id = $this->session->userdata('my_session_id');
                                $params = 'userid='.$user_info->id.'&username='.$user_info->nickname.'&sessionkey='.$my_session_id;
				redirect('http://dev.innoflex.vn/wordpress/?'.$params);
				//echo $params.$this->session->userdata('logged_in').$this->session->userdata('username').$this->session->userdata('id');
			}

		}
	}
        
        function generate_session_id($user_id){
            $session_id = md5($user_id.time());
            return $session_id;
        }
}

?>
